/*
 * Copyright (C) 2011 Olivier Pothin and contributors
 *
 * GNU General Public License v2.0
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

/**
 * 
 * @author Olivier Pothin
 *
 */
package opot.utils;

import java.util.Random;

import opot.db.WordProvider;
import opot.dto.Word;
import opot.exceptions.WordNotFoundException;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;

public class WordRandomizer {

	/**
	 * get random word from database
	 * @param excludeID excluded word
	 * @param range maximum id of word to fetch
	 * @return the fetched french word
	 * @throws WordNotFoundException 
	 *
	 */
	public static String getRandomFrenchWord(int excludeID, int range,Activity ctx) throws WordNotFoundException {
		
		return getRandomWord(excludeID, range, ctx, Word.Words.COLUMN_NAME_FRENCH);
	}
	
	public static String getRandomChineseWord(int excludeID, int range,Activity ctx) throws WordNotFoundException {
		
		return getRandomWord(excludeID, range, ctx, Word.Words.COLUMN_NAME_CHINESE);
	}
	
	protected static String getRandomWord(int excludeID, int range,Activity ctx,String translation) throws WordNotFoundException {
		int next = getRandomId(excludeID, range);
		
		Uri word = Uri.parse(
				"content://"+WordProvider.AUTHORITY+"/words/"+next);
		
		Cursor c = ctx.managedQuery(word, null, null, null, "created asc");
		if (c.moveToFirst()) {
			String t =  c.getString(c.getColumnIndex(translation));
			c.close();
			return t;
		}
		throw new WordNotFoundException();
	}
	
	public static int getRandomId(int excludeID, int range) {
		Random generator = new Random();
		int next = generator.nextInt(range)+1;
		while (next == excludeID){
			next = generator.nextInt(range)+1;
		}
		return next;
	}
}
